################################################################################
#   Copyright 2011 Shane C. Mason & Wrongdog.net                               
#
#   Licensed under the Apache License, Version 2.0 (the "License"); 
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.
#
################################################################################

import gettext
gettext.install('wrongnote')

from os import environ
import time

from wrongdog.wrongconfig import WrongConfig
WrongConfig(environ['HOME'] + "/.wrongnoteconfig")

import evernote.edam.userstore
import evernote.edam.type
from evernote.edam.error.ttypes import EDAMUserException

from evernote.edam.userstore import UserStore
from evernote.edam.notestore import NoteStore

from thrift.protocol import TBinaryProtocol
from thrift.transport import THttpClient


import logging
logging.basicConfig(level=logging.DEBUG)
aolog = logging.getLogger('wrongnote.ao')

CONF_EDAM_URL = "edam_url"
CONF_CONSUMER_KEY = "consumerkey"
CONF_CONSUMER_SECRET = "consumersecret"
CONF_USERNAME = "un"
CONF_PASSWORD = "pw"


WrongConfig().setValue( CONF_CONSUMER_KEY, 'scmason' )
WrongConfig().setValue( CONF_CONSUMER_SECRET, 'dae4fcbb64d851d0' )
WrongConfig().setValue( CONF_EDAM_URL, 'https://sandbox.evernote.com/edam/' )

class WrongNoteLoginError( Exception ):
    def __init__( self, message ):
        self.message = message
    
    def __str__( self ):
        return repr(self.message)
        
class WrongNoteAO:
    
    def __init__( self ):
        trans = THttpClient.THttpClient(WrongConfig().getValue(CONF_EDAM_URL) + "/user")
        prot = TBinaryProtocol.TBinaryProtocol(trans)
        self.__userstore = UserStore.Client( prot, prot )
        self.__user = None
        self.__auth = None
        

    def login( self ):
        stat = False
        msg = ""
        try:
            #get configuration values
            conf = WrongConfig();
            username = conf.getValue( CONF_USERNAME ).decode("base64_codec")
            password = conf.getValue( CONF_PASSWORD ).decode("base64_codec")
            key = conf.getValue( CONF_CONSUMER_KEY )
            secret = conf.getValue( CONF_CONSUMER_SECRET )
            
            self.__auth = self.__userstore.authenticate(username, password, key, secret)
            timeDiff = (self.__auth.expiration - self.__auth.currentTime)/1000.0
            self.__auth.expiration = time.time() + timeDiff
            self.__user = self.__auth.user
            stat = True
        except EDAMUserException as e:
            aolog.warn( "Error logging in: %s" % e )
            if( e.parameter == 'username' ):
                msg = _("Unknown username") 
            elif( e.parameter == 'password' ):
                msg = _("Incorrect password")
        except Exception as e:
            aolog.warn( "Unexpected error logging in: %s" % e)
            msg = _("Unexpected error")
            
        return ( stat, msg )
        

    def __getNoteStore( self ):
        noteStoreUrl = WrongConfig().getValue(CONF_EDAM_URL) + "/note/" + self.__user.shardId;
        
        noteStoreTrans = THttpClient.THttpClient(noteStoreUrl);
        noteStoreProt = TBinaryProtocol.TBinaryProtocol(noteStoreTrans);
        return NoteStore.Client(noteStoreProt, noteStoreProt)
    
    def __checkLogin( self ):
        if self.__user is None or self.__auth is None or self.__auth.expiration >= time.time(): 
            #then try to login
            (stat, message) = self.login()
            if( stat == False ):
                raise WrongNoteLoginError( _("Error on login") )
        
        
    def getNotebooks( self ):
        self.__checkLogin()
        noteBooks = self.__getNoteStore().listNotebooks(self.__auth.authenticationToken );
        
        return noteBooks
        
